package com.fessc.develop.job;

import com.fessc.develop.entity.dbvo.TPayment;
import com.fessc.develop.handler.PrePaymentPushHandler;
import com.fessc.develop.model.enums.EnumPushType;
import com.fessc.develop.model.enums.EnumTaskCode;
import com.fessc.develop.service.interfaces.ITPaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 银行直连预付款信息推送
 */
@Slf4j
@Service
public class PrePaymentPushJob extends ScheduleJob {

    @Resource
    private ITPaymentService paymentService;

    @Resource
    private PrePaymentPushHandler prePaymentPushHandler;

    @Override
    public String execute() {
        //查询等待发送银行的预付款信息，生成批次号，按批次发送银行
        log.info("推送预付款信息至银行处理");
        List<TPayment> paymentList = paymentService.getPrePaymentByContainType(getCCBBankId(), getTaskTermDate(), "N");

        log.info("按银行和机构编号分类预付款交易信息");
        Map<String, List<TPayment>> paymentMap = paymentList.stream().collect(Collectors.groupingBy(t -> t.getBankid() + t.getPlatid()));

        int batchTotal = getJobBatchtotal();
        log.info("按银行和机构编号生成预付款批次编号");
        for (Map.Entry<String, List<TPayment>> listEntry : paymentMap.entrySet()) {
            List<TPayment> updateBatchList = new ArrayList<TPayment>();
            List<TPayment> payList = listEntry.getValue();
            String batchSerialNo = "";
            for (int i = 0; i < payList.size(); i++) {
                TPayment tPayment = payList.get(i);
                if (i % batchTotal == 0) {
                    batchSerialNo = paymentService.getPaymentBatchNo(tPayment.getBankid().toString(), 8);
                }
                tPayment.setPaymentBatchNo(batchSerialNo);
                log.info("预付款批次号：" + tPayment.getPaymentBatchNo() + "，订单编号：" + tPayment.getSuborderno() + "，银行编号：" + tPayment.getBankid());
                updateBatchList.add(tPayment);
            }
            log.info("保存预付款批次号：总笔数" + updateBatchList.size() + "，银行编号" + payList.get(0).getBankid());
            //paymentService.updateBatchById(updateBatchList);
            paymentService.updatePaymentBatchNoById(updateBatchList);
        }

        //查询等待发送银行的预付款批次，包括由于发送超时未及时更新状态的批次
        List<TPayment> paymentBodyList = paymentService.getPrePaymentByContainTypeToPush(getCCBBankId(), getTaskTermDate(), "N");
        prePaymentPushHandler.prePaymentPush(paymentBodyList, EnumPushType.PAYMENT_PUSH.toString());

        return null;
    }

    @Override
    public String getTaskCode() {
        return EnumTaskCode.PRE_PAYMENT_PUSH.toString();
    }
}
